package leetcode;

/**
 * 设有n个线程，让这n个线程顺序交替打印0-99. 1<=n <= 100
 * @date 2020/3/10 22:44
 */
public class Code1114_Print1To100 implements Runnable{
    private int threadSeq;
    private static int threadNum;
    private static final int MAX_NUM = 100;
    private static volatile int counter = 0;

    private static final Object LOCK = new Object();

    public Code1114_Print1To100(int threadNum,int threadSeq) {
        this.threadNum = threadNum;//线程数量
        this.threadSeq = threadSeq;//每个线程维护自己的线程次序，0-threadNum-1
    }

    @Override
    public void run() {
        while (counter <= MAX_NUM){
            synchronized (LOCK){
                if(counter % threadNum == this.threadSeq){
//                    System.out.println(Thread.currentThread().getName()+"打印："+counter++);
                    //三个线程依次打印ABC
                    if(threadSeq == 0){
                        System.out.println(Thread.currentThread().getName()+"打印："+"A");
                    }else if(threadSeq == 1){
                        System.out.println(Thread.currentThread().getName()+"打印："+"B");
                    }else {
                        System.out.println(Thread.currentThread().getName()+"打印："+"C");
                    }
                    counter++;
                    LOCK.notifyAll();
                }else {
                    try {
                        LOCK.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int ThreadNum = 3;
        for (int i = 0; i < ThreadNum; i++) {
            new Thread(new Code1114_Print1To100(ThreadNum,i),"thread"+i).start();
        }
    }


}
/*
public class Main implements Runnable {

    private int count;
    private int id;
    public Main(int id,int count){
        this.id = id;
        this.count = count;
    }

    public void run(){

        for(int i = 1 ; i <= count ; i++){
            if(i % 3 == this.id){
                System.out.println("a");
            }else if(i % 3 == this.id){
                System.out.println("b");
            }else if(i % 3 == this.id){
                System.out.println("c");
            }

        }

    }
    public static void main(String[] args) {
        //Scanner in = new Scanner(System.in);
        //int a = in.nextInt();
        //System.out.println(a);
        int count = 30;

    }
}*/
